<template>
  <div>
    <el-tree
      :data="deptData"
      :props="treeProps"
      default-expand-all
      :show-checkbox="showCheckbox"
      :expand-on-click-node="false"
      @check-change="handleCheckChange"
      ref="treeRef"
      node-key="id"
      style="display: inline-block"
      @node-click="handleNodeClick"
    >
    </el-tree>
  </div>
</template>

<script>
import {getDeptTree} from "@/api/system/dept";

export default {
  name: "index",
  props: {
    // 父组件传递的初始部门数据
    initialData: {
      type: Array,
      default: () => []
    },
    // 父组件传递的选中部门数据
    selectedData: {
      type: Array,
      default: () => []
    },
    // 是否显示复选框
    showCheckbox: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      treeProps: {
        label: 'name',
        children: 'children'
      },
      // 部门树
      deptData: []
    }
  },
  created() {
    this.getDeptTree()
    this.getSelectedData()
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      getDeptTree()
        .then((r) => {
          this.deptData = [r.data];
          // 删除id为100的一级节点
          if (r.data.children[0].id === 100) {
            r.data.children.splice(0, 1);
          }
        }).catch(() => {})
    },
    // 处理节点选中变化事件，将选中数据传递给父组件
    handleCheckChange(data, checked, indeterminate) {
      // 传递选中节点数据
      this.$emit('selectionChange', data);
      this.clearTreeSelection()
    },
    // 清空树的选中状态
    clearTreeSelection() {
      this.$nextTick(() => {
        this.$refs.treeRef.setCheckedKeys([]);
      });
    },
    /** 获取选中节点数据（多选） */
    getSelectedData() {
      this.$nextTick(() => {
        this.$refs.treeRef.setCheckedKeys([this.selectedData]);
      })
    },
    /** 节点单击事件（单选） */
    handleNodeClick(node, data, event) {
      this.$emit('clickChange', node);
    }
  }
}
</script>

<style scoped>

</style>
